import java.io.File;

public class 检索指定文件夹硬盘大小 {
    public static void main(String[] args) {

        String folderPath = "C:\\Windows";
        File file = new File(folderPath);
        File[] files = file.listFiles();
        for (File file1 : files) {
            long size = getFolderSize(file1);
            String s = formatSize(size);
            if (s.contains("G"))
                System.out.println(file1.getName() +":文件夹大小: " + formatSize(size));
        }
    }
    // 递归计算文件夹大小
    private static long getFolderSize(File folder) {
        long size = 0;
        if (folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    size += getFolderSize(file);
                }
            }
        } else {
            size += folder.length();
        }
        return size;
    }


    // 格式化文件大小，将字节数转换为可读的格式
    private static String formatSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
        long tb = gb * 1024;

        if (size < kb) {
            return size + " B";
        } else if (size < mb) {
            return String.format("%.2f KB", (double) size / kb);
        } else if (size < gb) {
            return String.format("%.2f MB", (double) size / mb);
        } else if (size < tb) {
            return String.format("%.2f GB", (double) size / gb);
        } else {
            return String.format("%.2f TB", (double) size / tb);
        }
    }

}
